package com.lry.crawlers.video.pipeline;

import com.jnewbie.JHtml;
import com.jnewbie.request.JPage;
import com.jnewbie.request.JParam;
import com.lry.crawlers.information.service.InformationService;
import com.lry.crawlers.message.entity.Message;
import com.lry.crawlers.message.service.MessageService;
import com.lry.crawlers.util.StringTr;
import com.lry.crawlers.video.entity.Video;
import com.lry.crawlers.video.entity.VideoChapter;
import com.lry.crawlers.video.entity.VideoUpdate;
import com.lry.crawlers.video.service.VideoChapterService;
import com.lry.crawlers.video.service.VideoService;
import com.lry.crawlers.video.service.VideoUpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

@Component
public class VideoPipeline {
    public static Map<String,Object> cmap = new HashMap<>();
    @Autowired
    VideoService videoService;
    @Autowired
    VideoChapterService videoChapterService;
    @Autowired
    VideoUpdateService videoUpdateService;
    @Autowired
    MessageService messageService;
    @Autowired
    InformationService informationService;
    @Value("${lry.web-url}")
    private String url;



    public boolean process(Map<String,Object> map) {

        //判断数据是否不为空
        if(map!= null) {
            //判断数据类型
            if (map.get("key").equals("videoChapter")){
                Boolean is = video(map);
                if(is) {
                    chapter(map);
                }else {
                    return false;
                }
            }else if(map.get("key").equals("chapter")){
                chapter(map);
            }
        }
        return true;
    }
    //处理视频搜索
    public Boolean video(Map<String,Object> map) {
        Video video = null;
        String title = (String)  map.get("title");
        String descs = (String)  map.get("descs");
        String author = (String)  map.get("author");
        String director = (String)  map.get("director");
        String actor = (String)  map.get("actor");
        String region = (String)  map.get("region");
        String releaseTime = (String)  map.get("releaseTime");
        String videoType =(String)  map.get("videoType");
        String cover = (String)  map.get("cover");
        try {
            //提交封面到web端
            JHtml jHtml = new JHtml();
            jHtml.setTimeOut(10000);
            JParam jParam = new JParam();
            jParam.add("url", cover);
            jParam.add("ftitle",StringTr.TR(title));
            jParam.add("ititle",StringTr.TR(title)+".jpg");
            JPage post = jHtml.setParam(jParam).post(url+"/video/creation");
            int i = 0;
            while (!(post.getContent()!=null ? post.getContent().contains("成功") : false) && i<3){
                Thread.sleep(2000);
                post = jHtml.setParam(jParam).post(url+"/video/creation");
                i++;
            }
            if(post.getContent()!=null ? post.getContent().contains("成功") : false){
                cover = StringTr.TR(title)+"/" + StringTr.TR(title) + ".jpg";
            }else {
                cover = "defalult.jpg";
            }
        } catch (Exception e) {
            e.printStackTrace();
            cover = "defalult.jpg";
        }
        String updateTime = (String)  map.get("updateTime");
        String videoId = (String) map.get("videoId");
        Integer id = (Integer) map.get("id");
        video = new Video();
        video.setTitle(title.trim());
        video.setDirector(director.trim());
        video.setActor(actor.trim());
        video.setRegion(region.trim());
        video.setReleaseTime(releaseTime.trim());
        video.setCreationTime(new Date());
        video.setDescs(descs.trim());
        video.setVideoId(videoId);
        video.setVideoType(videoType.trim());
        video.setCover(cover);
        video.setVideoVariableId(id);
        video.setUpdateTime(updateTime);

        try {
            //添加到mysql
            int i= videoService.setVideo(video);
            if(i==0){
                messageService.setMessage(new Message("mysql视频入库失败,videoId:"+videoId,new Date()));
            }else{
                VideoUpdate videoUpdatec = new VideoUpdate();
                videoUpdatec.setVideoId(videoId);
                videoUpdatec.setVideoVariableId(id);
                videoUpdatec.setUpdateTime((String) map.get("updateTime"));
                String updateUrl = (String) map.get("updateUrl");
                updateUrl = "/" + updateUrl.split("/", 4)[3];
                videoUpdatec.setVideoUrl(updateUrl);
                videoUpdatec.setChapterNum(0);
                VideoUpdate videoUpdate = videoUpdateService.getVideoUpdate(videoId);
                try {
                    if (videoUpdate == null) {
                        videoUpdateService.setVideoUpdate(videoUpdatec);
                    }
                }catch(Exception e){
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw,true));
                    String infomsg = sw.toString();
                    messageService.setMessage(new Message("视频更新表入库失败,videoId:"+videoId+" .Extends："+infomsg,new Date()));
                }
                return true;
            }
        }catch (DuplicateKeyException e){
        }catch (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("视频入库失败,videoId:"+videoId+" .Extends："+infomsg,new Date()));
        }
        return false;
    }


    //处理视频章节
    public void chapter(Map<String,Object> map) {
        VideoChapter videoChapter = null;
        List<String> chapterTitle = (List<String>) map.get("chapterTitle");
        List<String> chapterUrl = (List<String>) map.get("chapterUrl");
        List<String> chapterId = (List<String>) map.get("chapterId");
        String videoId = (String) map.get("videoId");
        List<Integer> sortt = map.get("sortt") != null ? (List<Integer>) map.get("sortt") : null;
        List<VideoChapter> videoChapters = new ArrayList<>();
        for (int i = 0; i < chapterUrl.size(); i++) {
            videoChapter = new VideoChapter();
            videoChapter.setVideoId(videoId);
            videoChapter.setChapterPath(chapterUrl.get(i));
            videoChapter.setChapterId(chapterId.get(i));
            videoChapter.setTitle(chapterTitle.get(i).trim());
            videoChapter.setCreationTime(new Date());
            if (sortt != null)
                videoChapter.setSortt(sortt.get(i));
            else
                videoChapter.setSortt(i);
            videoChapters.add(videoChapter);
        }

        try {
            int i = videoChapterService.setVideoChapters(videoChapters);
            if (i == 0) {
                messageService.setMessage(new Message("视频章节保存失败,videoId:" + videoId, new Date()));
            } else {
                videoUpdateService.setVideoUpdateAdd(videoId, chapterUrl.size());
                String infId = (String) map.get("infId");
                String[] inf = infId.split("!!!");
                int o = informationService.updateCountVideo(inf[0], inf[1]);
                if(o==0){
                    Thread.currentThread().interrupt();
                }
            }
        }catch (DuplicateKeyException e) {
        } catch (Exception e) {
            System.out.println(videoChapters);
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw, true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("视频章节保存失败,videoId:" + videoId + " .Extends：" + infomsg, new Date()));
        }
        try {
            if (map.get("key").equals("chapter")) {
                videoService.setupdateTime(new Video(videoId, (String) map.get("updateTime")));
                videoUpdateService.setVideoUpdateUp(new VideoUpdate(videoId, (String) map.get("updateTime")));
            }
        } catch (DuplicateKeyException e) {
        } catch  (Exception e){
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw,true));
            String infomsg = sw.toString();
            messageService.setMessage(new Message("视频章节更新时间失败,videoId:"+videoId+" .Extends："+infomsg,new Date()));
        }

    }


}